package top.yaofengqiao.springcloudsimple.web.starter.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import top.yaofengqiao.springcloudsimple.auth.api.dto.TokenAuthResultDTO;
import top.yaofengqiao.springcloudsimple.common.constant.ResponseCode;
import top.yaofengqiao.springcloudsimple.common.util.AppException;

/**
 * @author yfq
 * @date 2024/6/17 15:01
 * @description
 */
@SuppressWarnings("all")
public class OauthUtil {

    /**
     * 获取当前登录用户的id
     */
    public static long currentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TokenAuthResultDTO tokenAuthResultDTO = (TokenAuthResultDTO) authentication.getPrincipal();

        if (tokenAuthResultDTO == null) throw new AppException(ResponseCode.NO_AUTHENTICATION);

        return tokenAuthResultDTO.getUserId();
    }

    /**
     * 获取当前登录用户
     */
    public static TokenAuthResultDTO currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        TokenAuthResultDTO tokenAuthResultDTO = (TokenAuthResultDTO) authentication.getPrincipal();

        if (tokenAuthResultDTO == null) throw new AppException(ResponseCode.NO_AUTHENTICATION);

        return tokenAuthResultDTO;
    }

}
